# region 准备工作：加载数据与库
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
# endregion

# region 加载鸢尾花数据集
iris = load_iris()
X = iris.data  # 特征：(150, 4)
y = iris.target  # 标签：0,1,2 对应三个类别
feature_names = iris.feature_names
target_names = iris.target_names
# endregion

# region 步骤 1：训练 LDA 模型并降维
# 初始化LDA，指定降维到2维（便于可视化）
lda = LinearDiscriminantAnalysis(n_components=2)
# 拟合并转换数据（降维）
X_lda = lda.fit_transform(X, y)  # 输出：(150, 2)
# endregion

# region 步骤 2：可视化降维结果
plt.figure(figsize=(10, 6))
# 按类别绘制降维后的数据点
for c, color, label in zip(range(3), ['r', 'g', 'b'], target_names):
    plt.scatter(X_lda[y == c, 0], X_lda[y == c, 1], c=color, label=label, alpha=0.7)
plt.xlabel('LDA Component 1')
plt.ylabel('LDA Component 2')
plt.title('Iris Data After LDA Projection (2D)')
plt.legend()
# plt.show()
# endregion


#

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=42  # 30%数据作为测试集
)

# 初始化LDA（默认保留所有有效维度，3类数据最多可降维到2维）
lda_clf = LinearDiscriminantAnalysis()
# 在训练集上拟合
lda_clf.fit(X_train, y_train)
# 预测测试集
y_pred = lda_clf.predict(X_test)




# 准确率
print(f"测试集准确率：{accuracy_score(y_test, y_pred):.4f}")

# 混淆矩阵
print("\n混淆矩阵：")
print(confusion_matrix(y_test, y_pred))

# 分类报告（精确率、召回率、F1值）
print("\n分类报告：")
print(classification_report(y_test, y_pred, target_names=target_names))